import { reactive, ref, toRefs, UnwrapNestedRefs } from "vue";
// S = object
export function useTable<T extends { list: any; total: number }, S extends { pageSize?: number }>(
  requestApi: (params: any) => RSP<T>,
  searchParams?: UnwrapNestedRefs<S>
) {
  const query = reactive({
    // keyword: "",
    parentId: 0,
    pageSize: searchParams?.pageSize ? searchParams?.pageSize : 10,
    // pageSize: 10,
    pageNum: 1,
  });
  const tableData = ref<T["list"]>([]);
  const total = ref(0);
  const keyword = ref("")

  async function fetchData() {
    const res = await requestApi({
      parentId: query.parentId,
      nameKeyword: keyword.value,
      pageSize: query.pageSize,
      pageNum: query.pageNum,
      ...searchParams,
    });
    tableData.value = res.data.list;
    total.value = res.data.total;
    // keyword.value = res.data.namekeyword
  }
  fetchData();

  const pageSizeChange = () => {
    fetchData();
  };
  const pageNumChange = () => {
    fetchData();
  };
  const search = () => {
    fetchData();
  };
  const emptyFn = () => {
    keyword.value = ""
    fetchData();
  }

  return {
    tableData,
    ...toRefs(query),
    total,
    pageNumChange,
    pageSizeChange,
    search,
    keyword,
    emptyFn,
    fetchData,
  };
}
